package com.javafamily.service.Impl;

import com.javafamily.bean.Pets;
import com.javafamily.repository.PetsRepository;
import com.javafamily.service.PetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PetsServiceImpl implements PetsService {

    @Autowired
    private PetsRepository repository;

    @Value("${server.port}")
    private int port;

    @Override
    public boolean savePets(Pets pets) {
        Pets obj = repository.save(pets);
        return obj != null ? true : false;
    }

    @Override
    public boolean removePetsById(Integer id) {
        if (repository.existsById(id)) {
            // 在数据库中指定的id若不存在，该方法会抛出异常
            repository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean modifyPets(Pets pets) {
        Pets obj = repository.save(pets);
        return obj != null ? true : false;
    }

    // 根据id查询
    @Override
    public Pets getPetsById(int id) {
        if (repository.existsById(id)) {
            // 在数据库中指定的id若不存在，该方法会抛出异常
            Pets pets = repository.getOne(id);
            // 添加端口号方便
//            pets.setName(pets.getName() + port);
            return pets;
        }
        Pets pets = new Pets();
        pets.setName("dog");
        return pets;
    }

    // 查询所有
    @Override
    public List<Pets> listAllPets() {
        List<Pets> pets = repository.findAll();

        for (Pets pets1 : pets) {
            pets1.setName(pets1.getName());
        }

        return repository.findAll();
    }
}
